#include "delay.h"

void Delay_us(uint32_t us){
    uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;
    uint32_t reload = SysTick->LOAD;

    ticks = us * reload / 1000;
    told = SysTick->VAL;
    while (1){
        tnow = SysTick->VAL;
        if (tnow != told){
            if (tnow < told){
                tcnt += told - tnow;
            }
            else{
                tcnt += reload - tnow + told;
            }
            told = tnow;
            if (tcnt >= ticks){
                break;
            }
        }
    }
}

void Delay_ms(uint16_t nms)
{
	uint32_t z;
	for(z=0;z<nms;z++) Delay_us(1000);
}

void Delay(uint32_t n)
{
	while(n--);
}
